﻿using Alipay.AopSdk.Core.Domain;
using Alipay.AopSdk.Core.Request;
using Alipay.AopSdk.Core.Response;
using Alipay.AopSdk.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Quartz.Logging;
using StackExchange.Redis;
using System;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Primitives;
using VOL.Core.Services;
using VOL.Entity.AttributeManager;
using VOL.SmartMecial.Dtos;
using System.Threading.Tasks;
using VOL.SmartMecial.IServices.PayInfoManage;

namespace VOL.WebApi.Controllers.SmartMecial
{
    [Route("api/PayconfigController")]
    [PermissionTable(Name = "PayconfigController")]
    public class PayconfigController : Controller
    {
        private readonly ILogger<PayconfigController> _logger;
        private readonly IPayConfirmService _payConfirmService;

        public PayconfigController(ILogger<PayconfigController> logger,IPayConfirmService payConfirmService )
        {
            _logger = logger;
            this._payConfirmService = payConfirmService;
        }
  

        /// <summary>   
        /// 支付宝支付
        /// </summary>
        /// <param name="tradeNo">商户订单号</param>
        /// <param name="subject">订单名称</param>
        /// <param name="totaAamount">付款金额</param>
        /// <param name="body">商品描述</param>
        /// <returns></returns>
        [HttpPost("AlipaySubmit")]
        public IActionResult AlipaySubmit([FromBody] AlipayDto dto)
        {
            _logger.LogInformation($"进入支付方法！");

            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.Body = dto.Body.Trim();
            model.Subject = dto.Subject.Trim();
            model.TotalAmount = dto.TotalAmount.Trim();
            model.OutTradeNo = dto.TradeNo.Trim();
            model.ProductCode = "FAST_INSTANT_TRADE_PAY";

            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

            // 修改回调地址配置
            var tmpUrl = Request.Scheme + "://" + Request.Host;

            var returnUrl = "http://localhost:9990/#/PayInfo?patientCode=" + dto.patientCode;
            // 异步通知地址 - 调用后端接口
            var notifyUrl = tmpUrl + "/api/PayconfigController/NotifyUrl";
            
            request.SetReturnUrl(returnUrl);
            request.SetNotifyUrl(notifyUrl);
            request.SetBizModel(model);

            try
            {
                _logger.LogInformation($"开始跳转到支付页面！");
                DefaultAopClient client = new DefaultAopClient(AlipayConfig.GatewayUrl, AlipayConfig.AppId, AlipayConfig.PrivateKey, "json", "2.0", AlipayConfig.SignType, AlipayConfig.AlipayPublicKey, AlipayConfig.CharSet, false);
              
                var response = client.PageExecute(request, null, "post");
                _logger.LogInformation($"组装的支付Form数据：{response.Body}");
                return Ok(new { success = true, formHtml = response.Body });
            }
            catch (Exception ex)
            {
                _logger.LogError($"支付报错：{ex.Message}");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 同步回调函数,由支付宝客户端立即重定向用户浏览器实现 
        /// </summary>
        /// <returns></returns>
        [HttpPost("ReturnUrl")]
        public ActionResult ReturnUrl()
        {


            //获取订单号，根据订单号查询订单状态，并更新订单状态
            StringValues outTradeNo = "";
            Request.Query.TryGetValue("out_trade_no", out outTradeNo);
            _payConfirmService.UpdatePaymentStatus(outTradeNo);
            ViewBag.PayFlag = 1;
            ViewBag.PayStatus = "支付完成-寻龙分金看缠山";
            return View();
        }

        /// <summary>
        /// 异步：通信异常或中断时回调函数,支付宝后台调用
        /// 支付宝的8次异步通知，每个异步通知调用频率:15s 3m 10m 30m 1h 2h 6h 15h
        /// </summary>
        /// <returns></returns>
        [HttpPost("NotifyUrl")]
        public ActionResult NotifyUrl()
        {
            //应该增加一个判断，判断订单状态是否已经修改为 已支付，如果修改为已支付，那么就不要再去修改订单状态了。
            ViewBag.PayFlag = 1;
            ViewBag.PayStatus = "支付完成";

            return View();
        }

    }
}
